package cn.gzmli.dtt.common.dao;

import cn.gzmli.dtt.common.entity.FileUpload;
import cn.gzmli.dtt.common.entity.PageInfo;
import cn.gzmli.dtt.common.utils.BaseDao;
import cn.gzmli.dtt.common.utils.BaseUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件上传Dao
 *
 * @author Pyj
 * @date 2019-08-01
 */
@Repository
public class FileUploadDao extends BaseDao<FileUpload> {

    public List getFilesList(HttpServletRequest request, PageInfo pageInfo) throws Exception {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT ")
            .append("f.id,f.name,f.type,f.size, ")
            .append("f.url,f.isScale,f.scalePath, ")
            .append("f.status,f.creatorId,f.createTime ")
            .append("FROM files f WHERE 1=1 ");
        Map<String, Object> map = new HashMap<>();
        if (!StringUtils.isEmpty(request.getParameter("id"))){
            map.put(" AND f.id = ?", request.getParameter("id"));
        }
        if (!StringUtils.isEmpty(request.getParameter("name"))){
            map.put(" AND f.name LIKE ?", "%" + request.getParameter("name") + "%");
        }
        if (!StringUtils.isEmpty(request.getParameter("type"))){
            map.put(" AND f.type LIKE ?", "%" + request.getParameter("type") + "%");
        }
        return BaseUtil.getData( sql , map, pageInfo, this, "createTime", false);
    }

    public FileUpload getFilesUploadByURL(String url) throws Exception {
        FileUpload fileUpload = new FileUpload();
        StringBuilder sql = new StringBuilder("SELECT * FROM files WHERE url='"+url+"'");

        List<FileUpload> fileUploads = getJdbcTemplate().query(sql.toString(), new Object[]{},
                new BeanPropertyRowMapper<FileUpload>(FileUpload.class));
        if (fileUploads.size() > 0){
            fileUpload = fileUploads.get(0);
        }
        return fileUpload;
    }

    public FileUpload getFilesUploadByScalePath(String scalePath) throws Exception {
        FileUpload fileUpload = new FileUpload();
        StringBuilder sql = new StringBuilder("SELECT * FROM files WHERE scalePath='"+scalePath+"'");

        List<FileUpload> fileUploads = getJdbcTemplate().query(sql.toString(), new Object[]{},
                new BeanPropertyRowMapper<FileUpload>(FileUpload.class));
        if (fileUploads.size() > 0){
            fileUpload = fileUploads.get(0);
        }
        return fileUpload;
    }
}
